package com.ycg.biquge.thread;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycg.biquge.pojo.Chapter;
import com.ycg.biquge.service.ChapterService;
import lombok.Data;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author YCG
 * @date 2024-05-03 19:19
 * @description 多线程获取chapter分页数据并修改content
 */
@Data
public class ChapterThread implements Runnable{

    private AtomicInteger current;

    private Semaphore semaphore;

    private AtomicBoolean hasNext;

    private final ChapterService chapterService = SpringUtil.getBean(ChapterService.class);

    @Override
    public void run() {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Page<Chapter> page = new Page<>(current.getAndIncrement(), 100);
        if (!page.hasNext()) {
            System.out.println("hasNext: false");
            hasNext.set(false);
        }
        List<Chapter> records = chapterService.page(page).getRecords();
        List<Chapter> chapters = records.parallelStream().peek(item -> {
            String content = item.getContent();
            String zipContend = Arrays.toString(ZipUtil.zlib(content, CharsetUtil.UTF_8, 1));
            item.setContent(zipContend);
            System.out.println("修改后的content=" + zipContend);
        }).toList();
        chapterService.updateBatchById(chapters);
        System.out.println("==================释放信号量");
        semaphore.release();
    }
}
